const express = require('express');

class StorageNode {
    constructor(port) {
        // 节点端口
        this.port = port;
        // 使用内存存储代替文件系统, 由于是demo演示，这里使用Map存储，实际生产环境应该使用文件系统存储
        this.storage = new Map();
        // 创建 Express 应用
        this.app = express();
        this.app.use(express.json());
        // 路由挂载
        this.setupRoutes();
    }

    setupRoutes() {
        // 存储分片
        this.app.post('/store', (req, res) => {
            const { hash, content } = req.body;

            if (!hash || !content) {
                return res.status(400).json({ error: '缺少必要参数' });
            }

            this.storage.set(hash, content);
            res.json({
                success: true,
                hash,
                storedAt: new Date().toISOString()
            });
        });

        // 检索分片
        this.app.get('/retrieve', (req, res) => {
            const hash = req.query.hash;

            if (!this.storage.has(hash)) {
                return res.status(404).json({ error: '分片不存在' });
            }

            res.json({
                success: true,
                hash,
                content: this.storage.get(hash)
            });
        });

        // 查看存储状态
        this.app.get('/status', (req, res) => {
            res.json({
                node: `node-${this.port}`,
                storedItems: this.storage.size,
                status: 'active'
            });
        });
    }

    start() {
        this.app.listen(this.port, () => {
            console.log(`存储节点运行在 http://localhost:${this.port}`);
        });
    }
}

// 启动两个存储节点
const node1 = new StorageNode(3001);
node1.start();

const node2 = new StorageNode(3002);
node2.start();